package org.dawning.shop.product.query.handler;

import org.axonframework.eventhandling.EventHandler;
import org.dawning.shop.common.events.product.ProductCreateEvent;
import org.dawning.shop.common.events.product.ProductOnSaleEvent;
import org.dawning.shop.common.events.product.ProductStopSellingEvent;
import org.dawning.shop.common.events.product.ProductUpdateEvent;
import org.dawning.shop.common.utils.BeanMapper;
import org.dawning.shop.product.query.entry.ProductEntry;
import org.dawning.shop.product.query.repository.ProductEntryRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by miou on 2017/6/12 0012.
 */
@Component
public class ProductEntryHandler {

    private Logger logger = LoggerFactory.getLogger(ProductEntryHandler.class);

    @Autowired
    private ProductEntryRepository repository;

    @EventHandler
    public void on(ProductCreateEvent event){
        //查询端监听事件，更新仓库
        logger.info("q create repository : "+event.toString());
        ProductEntry productEntry = BeanMapper.map(event.getProduct(),ProductEntry.class);
        productEntry.setId(event.getProductId());
        repository.save(productEntry);
    }

    @EventHandler
    public void on(ProductUpdateEvent event){
        logger.info("q update repository : "+event.toString());
        ProductEntry productEntry = BeanMapper.map(event.getProduct(),ProductEntry.class);
        productEntry.setId(event.getProductId().getIdentifier());
        repository.save(productEntry);
    }

    @EventHandler
    public void on(ProductOnSaleEvent event){
        logger.info("q update repository : "+event.toString());
        ProductEntry productEntry = repository.findOne(event.getProductId().getIdentifier());
        productEntry.setStatus(event.getProductStatus());
        repository.save(productEntry);
    }

    @EventHandler
    public void on(ProductStopSellingEvent event){
        logger.info("q update repository : "+event.toString());
        ProductEntry productEntry = repository.findOne(event.getProductId().getIdentifier());
        productEntry.setStatus(event.getProductStatus());
        repository.save(productEntry);
    }
}
